﻿using System;
using System.Data;
using System.Windows.Forms;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win;
using Dashboard.Expense.Business;
using System.Globalization;

namespace Dashboard.Expense
{
    public partial class FormAddExpenseLimit : Form
    {
        public int ID { get; set; }

        private DataTable _dataSource = new DataTable();

        public FormAddExpenseLimit()
        {
            InitializeComponent();
        }

        private void GenerateGridDataSource()
        {
            _dataSource = new DataTable();

            _dataSource.Columns.Add("ID", typeof(int));
            _dataSource.Columns.Add("AppTypeCode", typeof(string));
            _dataSource.Columns.Add("FeeCode", typeof(string));
            _dataSource.Columns.Add("Location", typeof(string));
            _dataSource.Columns.Add("Position", typeof(string));
            _dataSource.Columns.Add("Level", typeof(string));
            _dataSource.Columns.Add("FromTime", typeof(string));
            _dataSource.Columns.Add("ToTime", typeof(string));
            _dataSource.Columns.Add("LimitValue", typeof(decimal));
            _dataSource.Columns.Add("Currency", typeof(string));

            _dataSource.AcceptChanges();

            this.ultraGridMain.DataSource = _dataSource;
            this.ultraGridMain.DataBind();
        }

        private void toolStripButtonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void toolStripButtonSave_Click(object sender, EventArgs e)
        {
            if (this.comboBoxApplicationType.SelectedIndex == -1)
            {
                MessageBox.Show(this, "Please select one application type.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.comboBoxApplicationType.Focus();
                return;
            }

            if (this.comboBoxExpenseType.SelectedIndex == -1)
            {
                MessageBox.Show(this, "Please select one expense type.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.comboBoxExpenseType.Focus();
                return;
            }

            if (string.IsNullOrEmpty(this.comboBoxLocation.Text.Trim()))
            {
                MessageBox.Show(this, "Please select or input a location.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.comboBoxLocation.Focus();
                return;
            }

            if (this.comboBoxPosition.SelectedIndex == -1)
            {
                MessageBox.Show(this, "Please select one position.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.comboBoxPosition.Focus();
                return;
            }

            if (this.comboBoxLevel.SelectedIndex == -1)
            {
                MessageBox.Show(this, "Please select one level.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.comboBoxLevel.Focus();
                return;
            }

            if (this.maskedTextBoxExpTimeFrom.Text.Trim() != ":")
            {
                // 验证时间格式是否正确
                DateTime dtToTime;
                bool isValid = DateTime.TryParseExact(this.maskedTextBoxExpTimeFrom.Text, "HH:mm", new CultureInfo("en-US"), DateTimeStyles.None, out dtToTime);
                if (!isValid)
                {
                    MessageBox.Show(this, "From Time is invalid, please entry a valid time.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    this.maskedTextBoxExpTimeFrom.Focus();
                    this.maskedTextBoxExpTimeFrom.SelectAll();
                    return;
                }
            }

            if (this.maskedTextBoxExpTimeTo.Text.Trim() != ":")
            {
                // 验证时间格式是否正确
                DateTime dtToTime;
                bool isValid = DateTime.TryParseExact(this.maskedTextBoxExpTimeTo.Text, "HH:mm", new CultureInfo("en-US"), DateTimeStyles.None, out dtToTime);
                if (!isValid)
                {
                    MessageBox.Show(this, "To Time is invalid, please entry a valid time.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    this.maskedTextBoxExpTimeTo.Focus();
                    this.maskedTextBoxExpTimeTo.SelectAll();
                    return;
                }
            }

            decimal limitValue = 0;
            if (this.textBoxLimitValue.Text.Trim() != "")
            {
                if (!decimal.TryParse(this.textBoxLimitValue.Text.Trim(), out limitValue))
                {
                    MessageBox.Show(this, "Please input correct number.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.textBoxLimitValue.Focus();
                    return;
                }
            }
            else
            {
                MessageBox.Show(this, "Please input the limit value.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.textBoxLimitValue.Focus();
                return;
            }

            if (this.comboBoxCurrency.Text == "")
            {
                MessageBox.Show(this, "Please select one currency.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                this.comboBoxCurrency.Focus();
                this.comboBoxCurrency.SelectAll();
                return;
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;

                string applicationType = ((ComboBoxItem)this.comboBoxApplicationType.SelectedItem).Text;
                string expenseType = this.comboBoxExpenseType.Text;
                string location = this.comboBoxLocation.Text.Trim();
                string position = this.comboBoxPosition.Text;
                string level = this.comboBoxLevel.Text;
                string fromTime = this.maskedTextBoxExpTimeFrom.Text.Trim() == ":" ? "null" : "'" + DateTime.ParseExact(this.maskedTextBoxExpTimeFrom.Text, "HH:mm", new CultureInfo("en-US")).ToString("HH:mm") + "'";
                string toTime = this.maskedTextBoxExpTimeTo.Text.Trim() == ":" ? "null" : "'" + DateTime.ParseExact(this.maskedTextBoxExpTimeTo.Text, "HH:mm", new CultureInfo("en-US")).ToString("HH:mm") + "'";
                string currency = this.comboBoxCurrency.Text;

                Exp_ExpenseLimit eel = new Exp_ExpenseLimit();

                if (this.ID > 0)
                {
                    string sql = @"update exp_feelimit set apptypecode='{0}',feecode='{1}',location='{2}',
                                                           position='{3}',level='{4}',fromtime={5}, totime={6},
                                                           limitvalue={7},currency='{8}',updatedby='{9}',updateddate=getdate()
                                    where id={10}";

                    sql = string.Format(sql, applicationType, expenseType, location.Replace("'", "''"), position, level, fromTime, toTime, limitValue, currency,
                                        CommonBusiness.GetCurrentLoginUser(), this.ID);
                    eel.UpdateExpenseLimit(sql);

                    MessageBox.Show(this, "Save successfully.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                }
                else
                {
                    // 检查是否已经有类似的限额
                    if (eel.FormLimitExists(applicationType, expenseType, location, position, level))
                    {
                        MessageBox.Show(this, "Save failed, limit value has been set already.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    
                    string sql = @"insert into exp_feelimit(AppTypeCode,FeeCode,Location,Position,Level,FromTime,ToTime,LimitValue,Currency,InsertBy,InsertDate,UpdatedBy,UpdatedDate)
                               values('{0}','{1}','{2}','{3}','{4}',{5},{6},{7},'{8}','{9}',getdate(),'{10}',getdate())";

                    sql = string.Format(sql, applicationType, expenseType, location.Replace("'", "''"), position, level, fromTime, toTime, limitValue, currency,
                                        CommonBusiness.GetCurrentLoginUser(), CommonBusiness.GetCurrentLoginUser());

                    eel.InsertExpenseLimit(sql);

                    // 如果location没有在列表中，则保存
                    if (new BusinessBase().LocationExists(location) == false)
                    {
                        new BusinessBase().AddLocation(location);
                    }

                    // 将保存成功的记录加入到datasource中，显示在grid里面
                    DataRow row = _dataSource.NewRow();
                        row.ItemArray = new object[] {
                        0, applicationType, expenseType, location, position, level, 
                        (fromTime=="null" ? null : fromTime.Replace("'","")), 
                        (toTime == "null" ? null : toTime.Replace("'","")),
                        limitValue, currency
                    };
                    this._dataSource.Rows.InsertAt(row, 0);
                    this._dataSource.AcceptChanges();
                    this.ultraGridMain.ActiveRow = this.ultraGridMain.Rows[0];

                    // 重置Form
                    this.InitForm();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void InitForm()
        {
            this.LoadLocations();
            this.maskedTextBoxExpTimeFrom.Text = ":";
            this.maskedTextBoxExpTimeTo.Text = ":";
            this.textBoxLimitValue.Text = "";
        }

        private void ultraGridMain_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            // 自适应列宽
            e.Layout.AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.None;
            // 是否允许调整列宽
            e.Layout.Override.AllowColSizing = AllowColSizing.Free;
            // 是否允许移动栏位顺序
            e.Layout.Override.AllowColMoving = AllowColMoving.NotAllowed;

            // 设置Grid的Split窗口个数，建议设置为1--不允许Split
            e.Layout.MaxColScrollRegions = 1;
            e.Layout.MaxRowScrollRegions = 1;

            // 冻结列
            e.Layout.UseFixedHeaders = false;

            // 排序
            e.Layout.Override.HeaderClickAction = Infragistics.Win.UltraWinGrid.HeaderClickAction.SortSingle;

            // 不允许删除
            e.Layout.Override.AllowDelete = DefaultableBoolean.False;

            // 滚动提示
            e.Layout.Bands[0].ScrollTipField = "AppTypeCode";

            // 隐藏不需要显示的列
            e.Layout.Bands[0].Columns["ID"].Hidden = true;

            for (int i = 0; i < e.Layout.Bands[0].Columns.Count; i++)
            {
                e.Layout.Bands[0].Columns[i].CellActivation = Activation.NoEdit;
            }
        }

        private void FormAddExpenseLimit_Load(object sender, EventArgs e)
        {
            try
            {
                this.LoadAppTypes();
                this.LoadLocations();
                this.LoadPositions();
                this.LoadCurrency();

                this.GenerateGridDataSource();

                if (this.ID > 0)
                {
                    // load limit info for edit
                    DataTable limit = new Exp_ExpenseLimit().GetExpenseLimit(this.ID);

                    if (limit.Rows.Count > 0)
                    {
                        this.comboBoxApplicationType.Text = limit.Rows[0]["AppTypeCode"].ToString();
                        this.comboBoxExpenseType.Text = limit.Rows[0]["FeeCode"].ToString();

                        this.comboBoxLocation.Text = Convert.ToString(limit.Rows[0]["Location"]);
                        this.comboBoxPosition.Text = Convert.ToString(limit.Rows[0]["Position"]);
                        this.comboBoxLevel.Text = Convert.ToString(limit.Rows[0]["Level"]);
                        this.maskedTextBoxExpTimeFrom.Text = string.IsNullOrEmpty(Convert.ToString(limit.Rows[0]["FromTime"])) ? ":" : Convert.ToString(limit.Rows[0]["FromTime"]);
                        this.maskedTextBoxExpTimeTo.Text = string.IsNullOrEmpty(Convert.ToString(limit.Rows[0]["ToTime"])) ? ":" : Convert.ToString(limit.Rows[0]["ToTime"]);
                        this.textBoxLimitValue.Text = Convert.ToDecimal(limit.Rows[0]["LimitValue"]).ToString();
                        this.comboBoxCurrency.Text = limit.Rows[0]["Currency"].ToString();


                        this.comboBoxApplicationType.Enabled = false;
                        this.comboBoxExpenseType.Enabled = false;
                        this.comboBoxLocation.Enabled = false;
                        this.comboBoxPosition.Enabled = false;
                        this.comboBoxLevel.Enabled = false;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
        }

        private void LoadAppTypes()
        {
            Exp_ExpenseType eet = new Exp_ExpenseType();
            DataTable types = eet.QueryApplicationTypes();

            this.comboBoxApplicationType.Items.Clear();
            foreach (DataRow row in types.Rows)
            {
                this.comboBoxApplicationType.Items.Add(new ComboBoxItem() { Text = row["Code"].ToString(), Value = row["ID"].ToString() });
            }
        }

        private void LoadExpenses()
        {
            DataTable expenses = new Exp_ExpenseType().QueryExpenseTypes(int.Parse(((ComboBoxItem)this.comboBoxApplicationType.SelectedItem).Value.ToString()));
            this.comboBoxExpenseType.Items.Clear();

            foreach (DataRow row in expenses.Rows)
            {
                this.comboBoxExpenseType.Items.Add(row["Code"].ToString());
            }
        }

        private void LoadLocations()
        {
            DataTable locations = new BusinessBase().GetLocations();

            this.comboBoxLocation.Items.Clear();
            foreach (DataRow row in locations.Rows)
            {
                this.comboBoxLocation.Items.Add(row["pvalue1"].ToString());
            }
            this.comboBoxLocation.Text = "";
        }

        private void comboBoxApplicationType_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.LoadExpenses();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
        }

        private void LoadPositions()
        {
            DataTable positions = new Exp_ExpenseLimit().GetAllPositions();

            this.comboBoxPosition.Items.Clear();
            //this.comboBoxPosition.Items.Add("");
            foreach (DataRow row in positions.Rows)
            {
                this.comboBoxPosition.Items.Add(row["Position"].ToString());
            }
            //this.comboBoxPosition.SelectedIndex = 0;
        }

        private void LoadLevels()
        {
            /*
            if (this.comboBoxPosition.SelectedIndex == 0)
            {
                this.comboBoxLevel.Items.Clear();
                this.comboBoxLevel.Items.Add("");
            }
            else
            {
                DataTable levels = new Exp_ExpenseLimit().GetAllLevels(this.comboBoxPosition.Text);
                this.comboBoxLevel.Items.Clear();
                this.comboBoxLevel.Items.Add("");

                foreach (DataRow row in levels.Rows)
                {
                    this.comboBoxLevel.Items.Add(row["Level"].ToString());
                }
            }

            this.comboBoxLevel.SelectedIndex = 0;
            */
            DataTable levels = new Exp_ExpenseLimit().GetAllLevels(this.comboBoxPosition.Text);
            this.comboBoxLevel.Items.Clear();
            //this.comboBoxLevel.Items.Add("");

            foreach (DataRow row in levels.Rows)
            {
                this.comboBoxLevel.Items.Add(row["Level"].ToString());
            }
        }

        private void comboBoxPosition_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.LoadLevels();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
        }

        private void LoadCurrency()
        {
            DataTable currencies = new BusinessBase().GetCurrencies();

            this.comboBoxCurrency.Items.Clear();
            this.comboBoxCurrency.Items.Add(new BusinessBase().GetBaseCurrency());

            foreach (DataRow row in currencies.Rows)
            {
                this.comboBoxCurrency.Items.Add(row["pvalue1"].ToString());
            }

            this.comboBoxCurrency.SelectedIndex = 0;
        }
    }
}
